<template>
  <div>
    <el-form inline :model="formData" :rules="rules" ref="ruleForm">
      <!-- 表单元素 -->
      <el-form-item prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" :validate-event="false" />
      </el-form-item>
      <!-- 查询与情况的按钮 -->
      <el-button type="primary" icon="el-icon-search" @click="getCart(formData.username)">查询</el-button>
      <el-button type="default" @click="clear">重置</el-button>
    </el-form>
    <el-table :data="userCollection" stripe border empty-text="暂无收藏的商品" style="width: 100%">
      <el-table-column prop="goods_id" label="商品id" width="200"> </el-table-column>
      <el-table-column prop="goods_name" label="商品名称" width="400"> </el-table-column>
      <el-table-column label="商品图片" width="200">
        <template v-slot="{ row }">
          <el-image style="width: 50px; height: 50px" :src="row.goods_small_logo"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" width="200">
        <template v-slot="{ row }">
          <span>{{ row.goods_price.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-popconfirm :title="`确定删除用户 ${formData.username} 收藏夹中该商品吗?`" @onConfirm="deleteCollectGoods({ username: formData.username, goods_id: row.goods_id })">
            <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
export default {
  data() {
    return {
      formData: {
        username: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名' }]
      }
    }
  },
  computed: {
    ...mapState('user', ['userCollection'])
  },
  beforeDestroy() {
    // 清除用户收藏商品数据，保证下次进入该页面时为空
    this.clear()
  },
  methods: {
    ...mapMutations('user', ['getUserCollection', 'deleteCollectGoods', 'clearUserCollection']),
    getCart(username) {
      // 表单验证
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 通过，获取用户收藏商品数据
          this.getUserCollection(username)
        } else {
          this.clearUserCollection()
          return false
        }
      })
    },
    // 清除用户收藏商品数据
    clear() {
      this.formData.username = ''
      this.clearUserCollection()
    }
  }
}
</script>

<style></style>
